var contextPath = '';
	var scrollTop = 0;
var productId=undefined;
var productDetail=undefined;
$(function(){
	//加载商品信息
	productId=parseURL(window.location.search).id;
	/*if(productId==undefined){
		floatNotify.simple("非法请求!");

		history.back();
		return;
	}*/
	$.get(getRealPath()+"/product/productItemById",{id:productId},function(ret){
		if(ret&&ret.code==200){
			productDetail=ret.data;//页面存储商品信息
			if(productDetail==null||productDetail==undefined){//该商品可能被删除或者根本不存在
				floatNotify.simple("商品信息不存在!");
				history.back();
				return;
			}
			//console.log(productDetail);
			$("title").html(ret.data.full_name);
			var xxProductProductImagelist=ret.data.xxProductProductImagelist;
			mudiumImageHtml="";
			$("#mudiumImageList").html("");
			for(var i=0;i<xxProductProductImagelist.length;i++){
				mudiumImageHtml='<li style="display: table-cell; vertical-align: middle; max-width: 768px;">';
				mudiumImageHtml+='<a href="'+xxProductProductImagelist[i].source+'"><img style="max-width:100vw;max-height:80vw;margin:auto;" src="'+xxProductProductImagelist[i].medium+'"></a></li>';
				$("#mudiumImageList").append(mudiumImageHtml);
			}
			//图片轮播
			 TouchSlide({
				  	slideCell:"#slide",
				  	titCell:".hd ul", //开启自动分页 autoPage:true ，此时设置 titCell 为导航元素包裹层
				  	mainCell:".bd ul",
				  	effect:"left",
				  	autoPlay:false,//自动播放
				  	autoPage:true, //自动分页
				  	switchLoad:"_src" //切换加载，真实图片路径为"_src"
				  });
			 $("#basicInfo").html(String.formatmodel(templete.getProductBasicInfoTeml(),ret.data));

			 $("#introduction_a").html(ret.data.introduction);
			 initTab(productDetail.id);
			  $(".pingjia").html(productDetail.reviews);
			 // TODO 这个设置没有的时候图片显示不正确
			 /*var objs=$("#introduction_a img");
			 for(var i=0;i<objs.length;i++){
				 objs[i].style.width=(document.body.scrollWidth-50)+"px";
			 }
			 var objs1=$("#introduction_a div");
			 for(var i=0;i<objs1.length;i++){
				 objs1[i].style.width=(document.body.scrollWidth-50)+"px";
			 }
			 var objs2=$("#introduction_a ul");
			 for(var i=0;i<objs2.length;i++){
				 objs2[i].style.width=(document.body.scrollWidth-50)+"px";
			 }
			 var objs3=$("#introduction_a li");
			 for(var i=0;i<objs3.length;i++){
				 objs3[i].style.width=(document.body.scrollWidth-50)+"px";
			 }*/
			 initetails_con();
			 initNum();
			// 收藏状态获取
			 getShouCangByMidAndPid(productDetail.id);
		}

	},'json')
	// 详情数量减少
	function initetails_con(){
		$('.details_con .minus,.cart_count .minus').click(function(){
			var _index=$(this).parent().parent().index()-1;
			var _count=$(this).parent().find('.count');
			var _val=_count.val();
			if(_val>1){
				_count.val(_val-1);
				$('.details_con .selected span').eq(_index).text(_val-1);

			}
			if(_val<=2){
				$(this).addClass('disabled');
			}

		});

		// 详情数量添加
		$('.details_con .add,.cart_count .add').click(function(){
			var _index=$(this).parent().parent().index()-1;
			var _count=$(this).parent().find('.count');
			var _val=_count.val();
			$(this).parent().find('.minus').removeClass('disabled');
			_count.val(_val-0+1);
			$('.details_con .selected span').eq(_index).text(_val-0+1);

		});
	}


});

//加入购物车
function addShopCart() {
	//console.log(productDetail);
	//return;
	if (productDetail==undefined) {
		floatNotify.simple("商品信息加载错误!");
		return;
	}

	var addEntity={id:productDetail.id,
		image:productDetail.image,
		price:productDetail.price,
		quantity:$("#prodCount").val(),
		name:productDetail.full_name,
		seo_keywords:productDetail.seo_keywords,
		weight:productDetail.weight,
		is_free_shipping:productDetail.is_free_shipping};
	try{
		var shopCartInfo=jQuery.getCookie("shopCartInfo");

		if(shopCartInfo==""){
			jQuery.setCookie("shopCartInfo",JSON.stringify([addEntity]),null);
		}else{
			shopCartInfo= JSON.parse(shopCartInfo);
			var temStatus=true;
			for(var i=0;i<shopCartInfo.length;i++){
				if(shopCartInfo[i].id==addEntity.id){
					shopCartInfo[i].quantity=parseInt(shopCartInfo[i].quantity)+1;
					temStatus=false;
				}
			}
			//console.log(shopCartInfo);
			if(temStatus){
				shopCartInfo.push(addEntity);
			}
			jQuery.setCookie("shopCartInfo",JSON.stringify(shopCartInfo),null);
		}
		$("#totalNum").html(parseInt($("#totalNum").html())+1);
		floatNotify.simple("加入成功!");
		//console.info(getCookie("shopCartInfo"));
	}catch(e){
		floatNotify.simple("商品加入失败!");
	}
}

//立即购买
function buyNow() {
	if (productDetail==undefined) {
		floatNotify.simple("商品信息加载错误!");
		return;
	}
	//创建实体
	var addEntity={id:productDetail.id,
			image:productDetail.image,
			price:productDetail.price,
			quantity:$("#prodCount").val(),
			name:productDetail.full_name,
			seo_keywords:productDetail.seo_keywords,
			weight:productDetail.weight,
			is_free_shipping:productDetail.is_free_shipping,
			select:true};

	var shopCartInfo=jQuery.getCookie("shopCartInfo");

	if(shopCartInfo==""){
		jQuery.setCookie("shopCartInfo",JSON.stringify([addEntity]),null);
	}else{
		shopCartInfo= JSON.parse(shopCartInfo);
		var temStatus=true;
		for(var i=0;i<shopCartInfo.length;i++){
			if(shopCartInfo[i].id==addEntity.id){
				shopCartInfo[i].quantity=parseInt(shopCartInfo[i].quantity)+1;
				temStatus=false;
			}
		}
		//console.log(shopCartInfo);
		if(temStatus){
			shopCartInfo.push(addEntity);
		}
		jQuery.setCookie("shopCartInfo",JSON.stringify(shopCartInfo),null);
	}
	window.location.href=getRealPath()+"/cartToOrder.html";
	/*var prodId = productId;
	var prodCount = $("#prodCount").val();//购买数量
	jQuery.ajax({
		url : contextPath + "/addShopBuy",
		data : {
			"prodId" : prodId,
			"count" : prodCount,
			"sku_id" : $("#currSkuId").val(),
			"distUserName":distUserName
		},
		type : 'post',
		async : false, //默认为true 异步
		dataType : 'json',
		error : function(data) {
		},
		success : function(retData) {
			if (retData.status == 'LESS') {
				floatNotify.simple(prodLessMsg);
			} else if (retData.status == 'OWNER') {
				floatNotify.simple(failedOwnerMsg);
			} else if (retData.status == 'MAX') {
				floatNotify.simple(failedBasketMaxMsg);
			} else if (retData.status == 'ERR') {
				floatNotify.simple(failedBasketErrorMsg);
			}else if (retData.status == 'NO_SHOP') {
				floatNotify.simple("商家不存在");
			}else if (retData.status == 'OFFLINE') {
				floatNotify.simple("该商品已经下线,不能购买！");
			}else if (retData.status == "OK") {
				window.location.href = contextPath+"/shopcart";
			}
		}
	});*/

}


//获取参数页面
var paramResult;
function queryParameter(element,prodId){
	if(paramResult!=undefined){
		element.find('.desc-area').html(paramResult);
	}else{
		$.ajax({
			url: getRealPath()+"/queryDynamicParameter",
			data: {"productId":prodId},
			type:'post',
			async : true, //默认为true 异步
			error:function(data){
			},
			success:function(data){
				paramResult=data;
				//element.find('.desc-area').html(paramResult);
			}
		});
	}
	//element.addClass('hadGoodsContent');
 }
var  page=1;
var rows=10;
var reviewContent=undefined;
var prodId=undefined;
//获取评论
function queryProdComment(element,prodId){
	prodId=prodId;
	if(reviewContent!=undefined){
		return;
	}
  var data = {
	"productId":prodId
  };
  jQuery.ajax({
	url:getRealPath()+"/product/getreviewByProduct",
	data: data,
	type:'post',
	async : true, //默认为true 异步
	error: function(jqXHR, textStatus, errorThrown) {
 		 //alert(textStatus, errorThrown);
	},
	success:function(res){
		if(res&&res.code==200&&res.data.length>0){
			var datas=res.data;
			var html="";
			for(var i=0;i<datas.length;i++){
				html+='<li class="review_item">';
				html+='<div class="review-con" style="border-bottom: 1px solid #f0f0f0">';
				html+='<div class="review-img">';
				html+='<img src="'+datas[i].userImg+'"/>';
	        	html+='</div>';
				html+='<div class="review-user">';
	        	html+='<span>'+datas[i].nickname+'</span>';
	        	html+='</div>';
	        	html+='<div class="review-star">';
	        	for(var j=0;j<datas[i].score;j++){
	        		html+='<span><i class="i-fav i-fav-active"></i></span>';
	        	}
	        	html+='</div>';
	        	html+='</div>';
	    		html+='<div class="review-content">'+datas[i].content+" --"+datas[i].create_date;
	        	html+='</div>';
	        	html+='</li>';
			}
			element.html(html);
			reviewContent+=html;
			page+=1;
		}else{
			element.html("<div style='margin:0 auto;text-align:center;'>该商品还没有任何评论信息!</div>");
		}
	}
  });
 // element.addClass('hadGoodsContent');
}

//获取下一页评价
function next_comments(obj){
	/*var th = jQuery("#goodsContent .bd ul").eq(2);
	var page = parseInt(curPageNO)+1;
	var prodId = $("#prodId").val();*/
	var data = {
			 page:page,
			 rows:rows,
			"productId":prodId
		};
	var _this = $(".review");
	jQuery.ajax({
		url:getRealPath()+"/product/getreviewByProduct",
		data: data,
		type:'post',
		async : true, //默认为true 异步
		error: function(jqXHR, textStatus, errorThrown) {
	 		 //alert(textStatus, errorThrown);
		},
		success:function(res){
			if(res&&res.code==200&&res.data.length>0){
				_this.append(result);
			}else{
				$(obj).html("没有更多了！");
			}
			page+=1;
		}
	  });
}
function initTab(prodId){
	TouchSlide({
		slideCell:"#goodsContent",
		startFun:function(i,c){
			//var prodId = $("#prodId").val();
			if(i==1){//规格参数
				var th = jQuery("#goodsContent .bd ul").eq(i);
				if(!th.hasClass('hadGoodsContent')){
					queryParameter(th,prodId);
				}

				if($(window).scrollTop() > scrollTop){
					$(window).scrollTop(scrollTop);
				}
			}else if(i==2){//评价
				var th = jQuery("#goodsContent .bd ul").eq(i);
				if(!th.hasClass('hadConments')){
					queryProdComment(th,prodId);
				}
				if($(window).scrollTop() > scrollTop){
					$(window).scrollTop(scrollTop);
				}
			}else{
				if(scrollTop == 0){
					$(window).scrollTop(scrollTop);
					var hd_fav = $('.hd_fav');
					var position = hd_fav.position();
					scrollTop = position.top;
				}
			}
		},
	});

}
//初始化本商品数量
function initNum(){
	var shopCartInfo=jQuery.getCookie("shopCartInfo");
	if(shopCartInfo==""){
	}else{
		shopCartInfo= JSON.parse(shopCartInfo);
		var num=0;
		for(var i=0;i<shopCartInfo.length;i++){
			if(shopCartInfo[i].id==productDetail.id){
				num=shopCartInfo[i].quantity;
			}
		}
		$("#totalNum").html(num);
	}
}
//addInterest(this,416);添加收藏
var interest="add";
function addInterest(_this,productId){
	if($(_this).find("i").hasClass("i-fav-active")){//已经收藏过
		var interest="cancel";
	}
	loginInfo(function(userInfo){
		jQuery.ajax({
			url:getRealPath()+"/xxmember/updateFavorite",
			data: {memberId:userInfo.id,productId:productId,option:interest},
			type:'post',
			async : true, //默认为true 异步
			error: function(jqXHR, textStatus, errorThrown) {
				floatNotify.simple("操作失败!");
			},
			success:function(result){
				if($(_this).find("i").hasClass("i-fav-active")){
					$(_this).find("i").removeClass("i-fav-active");
				}else{
					$(_this).find("i").addClass("i-fav-active");
				}
				floatNotify.simple("操作成功!");
			}
		  });
	})
}
function getShouCangByMidAndPid(productId){
	loginInfo(function(userInfo){
		jQuery.ajax({
			url:getRealPath()+"/xxmember/getShouCangByMidAndPid",
			data: {memberId:userInfo.id,productId:productId},
			type:'get',
			async : true, //默认为true 异步
			error: function(jqXHR, textStatus, errorThrown) {
				//floatNotify.simple("操作失败!");
			},
			success:function(result){
				if(result&&result.code==200){
					if(result.data){
						$("#basicInfo .btn-fav").find("i").addClass("i-fav-active");
					}
				}
			}
		  });
	})
}